package cn.wolfcode.trip.base.util;

import com.aliyun.oss.OSSClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具
 */
public class UploadUtil {
	public static final String Path="F:/trip";

	public static final String ALIYUN_PAth="https://java29.oss-cn-shenzhen.aliyuncs.com";
	/**
	 * 处理文件上传
	 * @param file
	 * @param basePath
	 * @return  123.png
	 */
	public static String upload(MultipartFile file, String basePath) {
		//生成随机数
		String uuid = UUID.randomUUID().toString();
		//获取文件名称bg.jbp
		String orgFileName = file.getOriginalFilename();
		//获取后缀 .jpg
		String ext= "." + FilenameUtils.getExtension(orgFileName);
		//将随机数和后缀拼接
		String fileName = uuid + ext;

        try {
			//文件对象 路径+文件名
			File targetFile = new File(basePath, fileName);
			FileUtils.writeByteArrayToFile(targetFile, file.getBytes());

			return ALIYUN_PAth+"/upload/" + fileName;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}


	public static String uploadALiYun(MultipartFile file) {
		//生成随机数
		String uuid = UUID.randomUUID().toString();
		//获取文件名称bg.jbp
		String orgFileName = file.getOriginalFilename();
		//获取后缀 .jpg
		String ext= "." + FilenameUtils.getExtension(orgFileName);
		//将随机数和后缀拼接
		String fileName = uuid + ext;
		//文件夹
		String folder="upload/";



		// Endpoint以深圳为例
		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
		String accessKeyId = "LTAIlFb7QI1UJQUY";
		String accessKeySecret = "LbFJSY6jrov4A7AfXfY4iqjR8BDAKo";
		String bucket = "java29";

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		try {

            // 上传Byte数组。
            byte[] content = file.getBytes();
            ossClient.putObject(bucket, folder+fileName, new ByteArrayInputStream(content));
			// 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
			//ossClient.putObject(bucket, fileName, new File(basePath,fileName));
			//返回文件路径
			return "/upload/"+fileName;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			// 关闭OSSClient。
			ossClient.shutdown();
		}

		return null;
	}





}






















